// pages/cart/cart.js
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsList: {
      saveHidden: true,
      totalPrice: 0,
      allSelect: true,
      noSelect: false,
      list: [],
      listId: []
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.initCart()
  },

  /**
   * 初始化购物车
   */
  initCart: function () {
    let that = this,
      i, carts = []
    wx.showLoading({
      mask: true,
      title: app.globalData.loadText,
    })
    app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
      wx.request({
        url: app.globalData.hostAPI + '/api/v1/cart/index?access_token=' + accessToken,
        success: res => {
          if (res.data.status === 1) {
            wx.hideLoading()
            var data = res.data.data;

            for (i = 0; i < data.length; i++) {
              data[i].active = false
              if (data[i].is_lack == 0 || data[i].is_valid == 1) {
                carts.push(data[i])
              }
            }
            that.setData({
              goodsList: {
                list: carts
              },
            })
            that.setGoodsList(that.totalPrice(), that.allSelect(), that.noSelect(), carts);
          } else if(res.data.status === -10) {
            wx.hideLoading()
            wx.showModal({
              showCancel: false,
              title: '提示',
              content: '需要重新选择团长',
              success: res => {
                if(res.confirm) {
                  wx.navigateTo({
                    url: '../community/community',
                  })
                }
              }
            })
          } else {
            wx.hideLoading()
            wx.showToast({
              icon: 'none',
              title: res.data.msg,
            })
          }
        }
      })
    })
  },
  selectTap: function (e) {
    var index = e.currentTarget.dataset.index;
    var list = this.data.goodsList.list;
    if (index !== "" && index != null) {
      list[parseInt(index)].active = !list[parseInt(index)].active;
      console.log(list)
      this.setGoodsList(this.totalPrice(), this.allSelect(), this.noSelect(), list);
    }
  },

  bindAllSelect: function () {
    var currentAllSelect = this.data.goodsList.allSelect;
    var list = this.data.goodsList.list;
    if (currentAllSelect) {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.active = false;
      }
    } else {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i];
        curItem.active = true;
      }
    }

    this.setGoodsList(this.totalPrice(), !currentAllSelect, this.noSelect(), list);
  },

  jiaBtnTap: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index;
    var list = that.data.goodsList.list;
    that.setData({

    })
    if (index !== "" && index != null) {
      // 添加判断当前商品购买数量是否超过当前商品可购买库存
      var carShopBean = list[parseInt(index)];
      var carShopBeanStores = 0;
      var num = list[parseInt(index)].number;
      if (num < list[parseInt(index)].stock) {
        num++;
        app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
          wx.request({
            url: app.globalData.hostAPI + '/api/v1/cart/modify-num?access_token=' + accessToken + '&id=' + carShopBean.id,
            method: 'post',
            data: {
              num: num
            },
            header: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              if (res.data.status == 1) {
                list[parseInt(index)].number = num;
                that.setGoodsList(that.totalPrice(), that.allSelect(), that.noSelect(), list);
              } else {
                wx.showToast({
                  title: '操作失败！',
                  duration: 2000
                });
              }
            },
            fail: function () {
              wx.showToast({
                title: '网络异常！',
                duration: 2000
              });
            }
          })
        })
      } else {
        wx.showToast({
          title: '库存不足！',
          duration: 2000
        });
      }
    }
  },
  jianBtnTap: function (e) {
    var that = this
    var index = e.currentTarget.dataset.index;
    var list = that.data.goodsList.list;
    if (index !== "" && index != null) {
      // 添加判断当前商品购买数量是否超过当前商品可购买库存
      var carShopBean = list[parseInt(index)];
      var carShopBeanStores = 0;
      var num = list[parseInt(index)].number;
      if (num > 1) {
        num--;
        app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
          wx.request({
            url: app.globalData.hostAPI + '/api/v1/cart/modify-num?access_token=' + accessToken + '&id=' + carShopBean.id,
            method: 'post',
            data: {
              num: num
            },
            header: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              if (res.data.status == 1) {
                list[parseInt(index)].number = num;
                that.setGoodsList(that.totalPrice(), that.allSelect(), that.noSelect(), list);
              } else {
                wx.showToast({
                  title: '操作失败！',
                  duration: 2000
                });
              }
            },
            fail: function () {
              wx.showToast({
                title: '网络异常！',
                duration: 2000
              });
            }
          })
        })
      } else {
        wx.showToast({
          title: '最小购买量为1！',
          duration: 2000
        });
      }
    }
  },

  /**
   * 删除购物车
   */
  delItem: function (e) {
    let that = this,
      cart_id = e.currentTarget.dataset.cid,
      index = e.currentTarget.dataset.index,
      list = this.data.goodsList.list
    wx.showModal({
      title: '提示',
      content: '是否删除产品',
      success: res => {
        if (res.confirm) {
          app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
            wx.request({
              url: app.globalData.hostAPI + '/api/v1/cart/del?access_token=' + accessToken,
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                ids: cart_id
              },
              success: res => {
                if (res.data.status === 1) {
                  that.initCart()
                  list.splice(index, 1);
                  that.setGoodsList(that.totalPrice(), that.allSelect(), that.noSelect(), list);
                }
              }
            })
          })
        }
      }
    })
  },


  totalPrice: function () {
    var list = this.data.goodsList.list;
    var total = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        total += parseFloat(curItem.discount_price) * curItem.number;
      }
    }
    total = parseFloat(total.toFixed(2)); //js浮点计算bug，取两位小数精度
    return total;
  },
  allSelect: function () {
    var list = this.data.goodsList.list;
    var allSelect = false;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (curItem.active) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    return allSelect;
  },
  noSelect: function () {
    var list = this.data.goodsList.list;
    var noSelect = 0;
    for (var i = 0; i < list.length; i++) {
      var curItem = list[i];
      if (!curItem.active) {
        noSelect++;
      }
    }
    if (noSelect == list.length) {
      return true;
    } else {
      return false;
    }
  },
  setGoodsList: function (total, allSelect, noSelect, list) {
    var listId = [];
    for (var k in list) {
      if (list[k].active) {
        listId.push(list[k].id);
      }
    }
    this.setData({
      goodsList: {
        totalPrice: total,
        allSelect: allSelect,
        noSelect: noSelect,
        list: list,
        listId: listId
      }
    });
  },

  /**
   * cartConfirm
   */
  cartConfirm: function () {
    var list = this.data.goodsList.list;
    list = list.filter(function (curGoods) {
      return curGoods.active;
    });
    if (this.data.goodsList.totalPrice == 0) {
      wx.showToast({
        icon: 'none',
        title: '请选择商品',
      })
      return false
    }
    wx.navigateTo({
      url: '../confirm/confirm?is_cart=1&cart_ids=' + JSON.stringify(this.data.goodsList.listId) + '&goods=' + JSON.stringify(list)
    })
  },

  /**
   * 
   */
  longTap: function (e) {
    console.log(e)
    let that = this
    wx.showModal({
      title: '提示',
      content: '是否删除商品',
      success: res => {
        if (res.confirm) {
          app.getAccessToken(app.getPageUrl(getCurrentPages())).then(function (accessToken) {
            wx.request({
              url: app.globalData.hostAPI + '/api/v1/cart/del?access_token=' + accessToken,
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              data: {
                ids: e.currentTarget.dataset.cid
              },
              success: res => {
                if (res.data.status === 1) {
                  that.initCart()
                }
              }
            })
          })
        }
      }
    })
  }
})